﻿using Microsoft.AspNetCore.Authorization;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
using System.Security.Claims;
using gt.dotnetcore.webapi.extension.Services;
using Microsoft.AspNetCore.Authorization.Infrastructure;
using Microsoft.AspNetCore.Mvc.Filters;
using gt.dotnetcore.webapi.extension.Entity;

namespace gt.dotnetcore.webapi.extension.Authorizations
{
    public class PermissionCheckAuthorizationHandler : AuthorizationHandler<ClaimsAuthorizationRequirement>
    {
        public PermissionCheckAuthorizationHandler(IPermissionCheckService checkService)
        {
            CheckService = checkService ?? throw new ArgumentNullException(nameof(checkService));
        }

        public IPermissionCheckService CheckService { get; }

        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, ClaimsAuthorizationRequirement requirement)
        {
            var appkey = context.User.Identity?.Name;
            var authContext = context.Resource as AuthorizationFilterContext;

            var email = context.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value;

            var controllerName = authContext.ActionDescriptor.RouteValues["controller"];
            var actionName = authContext.ActionDescriptor.RouteValues["action"];

            var controllerAction = string.Concat(controllerName, "/", actionName);

            if (CheckService.Check(appkey, controllerAction))
            {
                context.Succeed(requirement);
            }
            else
            {
                context.Fail();
            }

            return Task.CompletedTask;
        }

    }
}
